package com.lcz.authority.admin.controller.system;

import com.lcz.authority.admin.service.SysResourceService;
import com.lcz.authority.admin.web.service.SysPermissionService;
import com.lcz.authority.common.annotation.ApiResource;
import com.lcz.authority.common.core.page.PageResult;
import com.lcz.authority.common.domain.R;
import com.lcz.authority.common.domain.entity.SysResourceEntity;
import com.lcz.authority.common.enums.AppCodeEnum;
import com.lcz.authority.common.enums.ResBizTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.lcz.authority.common.utils.SecurityUtils.getUserId;

/**
 * @author lcz
 * @desc 资源管理控制器
 * @mail lcz_0130@163.com
 * @date 2024/05/06
 */

@RestController
@RequestMapping("/system/resource")
@ApiResource(name = "资源管理", resBizType = ResBizTypeEnum.SYSTEM, appCode = AppCodeEnum.SYSTEMMODULES)
@Api(tags = "资源管理")
public class SysApiResourceController {
    @Autowired
    private SysResourceService resourceService;
    @Autowired
    private SysPermissionService permissionService;

    @PreAuthorize("@ss.hasPermi('system:resource:list')")
    @GetMapping(value = "/list", name = "接口资源-查询接口列表")
    @ApiOperation("查询接口列表")
    public R list(SysResourceEntity sysResourceEntity) {
        PageResult<SysResourceEntity> list = resourceService.page(sysResourceEntity);
        return R.ok().put(list);
    }

    @GetMapping(value = "/roleApiTreeselect/{roleId}", name = "加载对应角色资源列表树")
    @ApiResource(name = "加载对应角色资源列表树")
    @ApiOperation("加载对应角色资源列表树")
    public R roleMenuTreeSelect(@PathVariable("roleId") String roleId) {
        List<SysResourceEntity> resources = resourceService.selectApiResourceList(getUserId());
        R ajax = R.ok();
        ajax.put("checkedKeys", resourceService.selectResourceListByRoleId(roleId));
        ajax.put("resources", resourceService.buildResourceTreeSelect(resources));
        return ajax;
    }

    @PutMapping(value = "/roleApi", name = "修改对应角色api资源")
    @ApiResource(name = "修改对应角色api资源")
    @ApiOperation("修改对应角色api资源")
    public R editRoleResource(String roleId, String[] resourceIds) {
        resourceService.editRoleResource(roleId, resourceIds);
        //更新redis缓存权限数据
        permissionService.resetLoginUserRoleCache(roleId);
        return R.ok();
    }


}
